package ynu.edu.achitecturework.service;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import ynu.edu.achitecturework.dao.DeviceDAO;
import ynu.edu.achitecturework.dao.GreenhouseDAO;
import ynu.edu.achitecturework.dao.UserDAO;
import ynu.edu.achitecturework.entity.Device;
import ynu.edu.achitecturework.entity.Greenhouse;
import ynu.edu.achitecturework.entity.User;

@Service
@RequiredArgsConstructor
public class DataInitializationService implements CommandLineRunner {

    private final GreenhouseDAO greenhouseDAO;
    private final DeviceDAO deviceDAO;
    private final UserDAO userDAO;
    private final PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) {
        initializeUser();
        initializeGreenhouse();
        initializeDevices();
    }

    private void initializeUser() {
        if (userDAO.findByUsername("admin") == null) {
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode("admin"));
            userDAO.save(admin);
        }
    }

    private void initializeGreenhouse() {
        if (greenhouseDAO.findByBoxNo("300023040198") == null) {
            Greenhouse greenhouse = new Greenhouse();
            greenhouse.setName("云南大学大棚");
            greenhouse.setAddress("云南大学");
            greenhouse.setArea(300.0);
            greenhouse.setBoxNo("300023040198");
            greenhouseDAO.save(greenhouse);
        }
    }

    private void initializeDevices() {
        Greenhouse greenhouse = greenhouseDAO.findByBoxNo("300023040198");
        if (greenhouse == null) return;

        // 初始化土壤含水率检测器
        initializeDevice(greenhouse, "土壤含水率检测器", "327061430532576246", "MOISTURE", "%");

        // 初始化土壤温度检测器
        initializeDevice(greenhouse, "土壤温度检测器", "327061430532576250", "TEMPERATURE", "℃");

        // 初始化土壤电导率检测器
        initializeDevice(greenhouse, "土壤电导率检测器", "327061430531527664", "CONDUCTIVITY", "us/cm");

        // 初始化土壤PH值检测器
        initializeDevice(greenhouse, "土壤PH值检测器", "327061430532576241", "PH", "pH");

        // 初始化土壤氮含量检测器
        initializeDevice(greenhouse, "土壤氮含量检测器", "327061430532576242", "NITROGEN", "mg/kg");

        // 初始化摄像头
        initializeDevice(greenhouse, "监控摄像头", "AB9831171", "CAMERA", null);
    }

    private void initializeDevice(Greenhouse greenhouse, String name, String serialNumber,
                                  String deviceType, String unit) {
        if (deviceDAO.findBySerialNumber(serialNumber) == null) {
            Device device = new Device();
            device.setName(name);
            device.setSerialNumber(serialNumber);
            device.setDeviceType(deviceType);
            device.setUnit(unit);
            device.setGreenhouse(greenhouse);
            deviceDAO.save(device);
        }
    }
}